package com.cks.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cks.eduservice.entity.EduSubject;
import com.cks.eduservice.entity.excel.SubjectData;
import com.cks.eduservice.service.EduSubjectService;
import com.cks.servicebase.exceptionhandler.CksException;

public class subjectExcelListener extends AnalysisEventListener <SubjectData>{

    //因为subjectExcelListener不能交给springboot管理，需要自己new,不能注入其他对像
    //不能实现数据库操作
    public EduSubjectService subjectService;
    public  subjectExcelListener(){
    }
    public  subjectExcelListener(EduSubjectService subjectService){
        this.subjectService=subjectService;
    }

    //读取excel内容一行一行的读
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
          if (subjectData==null){
              throw  new CksException(20001,"文件数据为空");
          }
          //一行一行的读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        //判断一级分类是否重复
        EduSubject eduoneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
          if(eduoneSubject==null){  // 没有一级分类，添加
              eduoneSubject= new EduSubject();
              eduoneSubject.setParentId("0");
              eduoneSubject.setTitle(subjectData.getOneSubjectName());
              subjectService.save(eduoneSubject);
          }
           //得到一级分类的id值
         String id = eduoneSubject.getId();

        //判断二级分类是否重复
        EduSubject edutwoSubject = this.existTwoSubject(subjectService, subjectData.getOneSubjectName(),id);
        if(edutwoSubject==null){  // 没有二级分类，添加
            edutwoSubject = new EduSubject();
            edutwoSubject.setParentId(id);
            edutwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(edutwoSubject);
        }

    }
    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject>  wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",0);
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject>  wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject towSubject = subjectService.getOne(wrapper);
        return towSubject;
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
